package com.zoweunion.mechanic.service.base.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.dao.base.PartsDao;
import com.zoweunion.mechanic.dao.base.UpkeepDao;
import com.zoweunion.mechanic.model.things.ThingsData;
import com.zoweunion.mechanic.service.base.UpkeepService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 保养套餐业务类
 * @author Administrator
 *
 */
@Service
@Transactional
public class UpkeepServiceImpl implements UpkeepService {

	@Autowired
	private PartsDao partsDao;
	@Autowired
	private UpkeepDao upkeepDao;
	@Autowired
	private ToolCarDataMapper toolCarDataMapper;

	@Autowired
	private OwnerDao ownerDao;
	
	@Override
	@Transactional(readOnly=true)
	public Map<String, Object> getUpkeepInfo(Map<String, Object> reqMap) {
		List<Map<String, Object>> partsByUpkeep_id = upkeepDao.getPartsByUpkeep_id(reqMap);
		Map<String, Object> upkeepById = upkeepDao.getUpkeepById(reqMap);
		
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("partsInfo", partsByUpkeep_id);
		resultMap.put("upkeepInfo", upkeepById);
		return resultMap;
	}

	@Override
	public int delete(Map<String, Object> reqMap) throws MyException {
	    int i = upkeepDao.countById(reqMap);
	    if (i == 0) {
            return upkeepDao.deleteUpkeepById(reqMap);
        } else {
	        throw new MyException(Constants.CODE_HANDEL_FAILED, "当前保养套餐正在被使用，无法删除");
        }
	}


	@Override
	public int addUpkeep(Map<String, Object> reqMap) throws MyException {
		//1插入保养套餐数据
		int result=0;
        String u_id = UuidUtil.get32UUID();
        reqMap.put("id", u_id);
		result = upkeepDao.getUpkeepByTime(reqMap);
		if (result > 0) {
		    throw new MyException(Constants.CODE_HANDEL_FAILED, "当前保养套餐已存在，请重新填写");
        } else {
            result += upkeepDao.addUpkeep(reqMap);
        }
		
		//2插入保养套餐_配件关联数据
		
		reqMap.put("u_id", u_id);//保养套餐id
		//获取配件集合
		if(reqMap.get("parts")==null) {
			return result;
		}
		List<Object> parts = JSONObject.parseObject(reqMap.get("parts").toString(), List.class);
		for (Object part : parts) {
			//将配件集合中的每一个字符串转为map
			Map<String,Object> partMap = JSONObject.parseObject(part.toString(), Map.class);
			reqMap.put("id",UuidUtil.get32UUID());//主id
			reqMap.put("d_id", partMap.get("id"));//配件id
			reqMap.put("quantity", partMap.get("quantity"));//配件数量
			reqMap.put("dictionaries_name", partMap.get("dictionaries_name"));
			reqMap.put("dictionaries_model", partMap.get("dictionaries_model"));
			reqMap.put("dictionaries_unit", partMap.get("dictionaries_unit"));
			reqMap.put("dictionaries_code", partMap.get("dictionaries_code"));
			reqMap.put("dictionaries_type", partMap.get("dictionaries_type"));
			reqMap.put("dictionaries_price", partMap.get("dictionaries_price"));
			result+=upkeepDao.addUpkeep_dictionaries(reqMap);
		}
		return result;
	}

	@Override
	public int editUpkeep(Map<String, Object> reqMap) {
		int result=0;
		//1根据id修改保养套餐数据
		result+=upkeepDao.update(reqMap);
		//2.根据保养id删除相应的保养_配件关联数据
		upkeepDao.delelteUpkeep_dictionaries(reqMap);
		
		//3插入新的保养套餐_配件关联数据
		reqMap.put("u_id", reqMap.get("id"));//保养套餐id
		//获取配件集合
		if(reqMap.get("parts")==null) {
			return result;
		}
		List<Object> parts = JSONObject.parseObject(reqMap.get("parts").toString(), List.class);
		for (Object part : parts) {
			//将配件集合中的每一个字符串转为map
			Map<String,Object> partMap = JSONObject.parseObject(part.toString(), Map.class);
			reqMap.put("id",UuidUtil.get32UUID());//主id
			reqMap.put("d_id", partMap.get("id"));//配件id
			reqMap.put("quantity", partMap.get("quantity"));//配件数量
			reqMap.put("dictionaries_name", partMap.get("dictionaries_name"));
			reqMap.put("dictionaries_model", partMap.get("dictionaries_model"));
			reqMap.put("dictionaries_unit", partMap.get("dictionaries_unit"));
			reqMap.put("dictionaries_code", partMap.get("dictionaries_code"));
			reqMap.put("dictionaries_type", partMap.get("dictionaries_type"));
			reqMap.put("dictionaries_price", partMap.get("dictionaries_price"));
			result+=upkeepDao.addUpkeep_dictionaries(reqMap);
		}
		return result;
	}

	@Override
	@Transactional(readOnly=true)
	public Map<String, Object> getPageQuery(Map<String, Object> reqMap) {
		//1.设置分页的limit和offset
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		int limit = Integer.valueOf(pageMap.get("limit").toString());
            //2.查询分组过滤后的总记录数
        int total = upkeepDao.countByModeId(reqMap);

            //3执行分页查询
        List<Map<String, Object>> list = upkeepDao.pageQuery2(reqMap);
		
		//4包装结果集  总条数 总页数 数据集
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		int pages=(total+limit-1)/limit;//总页数  需要有余进一
		
		resultMap.put("total", total);
		resultMap.put("pages", pages);
		resultMap.put("list", list);
		return resultMap;
	}

	@Override
	@Transactional(readOnly=true)
	public List<Map<String, Object>> getUpkeep_timeByCondition(Map<String, Object> reqMap) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (Orgin.getString(reqMap, "car_model_id") != null && !Orgin.getString(reqMap, "car_model_id").equals("")) {
            list = upkeepDao.getUpkeep_timeByCondition(reqMap);
        }
        return list;
    }


	@Override
	public int deleteByCarInfo(Map<String, Object> reqMap) throws MyException {
	    List<Map<String, Object>> list = upkeepDao.getUpkeepByModeId(reqMap);
	    if (list.size() > 0) {
            int count = 0;
            for (Map<String, Object>map : list) {
                int i = upkeepDao.countById(map);
                count = count+i;
            }
            if (count > 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED, "该型号设备部分套餐使用中，无法删除");
            } else {
                for (Map<String, Object>map : list) {
                    this.delete(map);
                }
                return 1;
            }
        } else {
	        throw new MyException(Constants.CODE_ERROR, "当前型号车辆不存在套餐，请核实后再次尝试");
        }
	}

	@Override
	public Map<String, Object> getUpkeepTime(Map<String, Object> reqMap) {
		List<Map<String, Object>> partsByUpkeep_id = upkeepDao.getPartsByUpkeep_id(reqMap);
		Map<String, Object> upkeepById = upkeepDao.getUpkeepById(reqMap);

		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("partsInfo", partsByUpkeep_id);
		resultMap.put("upkeepInfo", upkeepById);
		return resultMap;
	}

	@Override
	public Integer getUpkeepDuration(Map<String, Object> reqMap) {
		Map<String,Object> carsMap = ownerDao.getCarInfoById(reqMap);
		getUpkeep_timeByCondition(carsMap);
		//拼接参数
		String opcpathUrl = Constants.THINGS_URL_ONE+carsMap.get("opc_path").toString();
		//调用新思联接口
		String thingsInfo = HttpClient.doGet(opcpathUrl,Constants.interface_account, Constants.unify_account);
		JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
		int number=0;
		if (null!=thingsArray&&thingsArray.size() > 0) {
			JSONObject thingsObject = (JSONObject) thingsArray.get(0);
			List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject
					.get("OPCValueList");
			if("运行小时".equals(OPCValueList.get(3).get("ValueName"))){
				number= Integer.parseInt(carsMap.get("running").toString())+(int)(Double.parseDouble( OPCValueList.get(3).get("DataValue").toString()));
			}
		}else{
			number= Integer.valueOf(carsMap.get("running").toString());
		}
		return number;
	}

	@Override
	public Integer getUpkeepDurationNew(Map<String, Object> reqMap) throws MyException {
		Map<String, Object> carsMap = ownerDao.getCarInfoById(reqMap);
		getUpkeep_timeByCondition(carsMap);

		String thingsId = carsMap.get("things_id").toString();
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
		// 获取车辆最新设备数据
		Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, thingsId);

		int number;
		if (null != carDataMap) {
			number = Integer.valueOf(carDataMap.get("OperatingHours").toString());
		} else {
			number = Integer.valueOf(carsMap.get("running").toString());
		}
		return number;
	}

	@Override
	public Map<String, Object> getUpkeepById(String m_id) {
		Map<String,Object> reqMap=new HashMap<>();
		reqMap.put("id",m_id);
		return this.upkeepDao.getUpkeepById(reqMap);
	}

	@Override
	public Map<String, Object> maintenanceRecommendation(Map<String, Object> reqMap) {
		Map<String,Object> result=new HashMap<>();
		Map<String,Object> carsMap = ownerDao.getCarInfoById(reqMap);
		List<Map<String,Object>> maintenanceRecommendation =upkeepDao.getUpkeep_timeByCondition(carsMap);

		//拼接参数
		String opcpathUrl = Constants.THINGS_URL_ONE+carsMap.get("opc_path").toString();
		//调用新思联接口
		String thingsInfo = HttpClient.doGet(opcpathUrl,Constants.interface_account, Constants.unify_account);
		JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
		int number=0;
		if (null!=thingsArray&&thingsArray.size() > 0) {
			JSONObject thingsObject = (JSONObject) thingsArray.get(0);
			List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject
					.get("OPCValueList");
			if("运行小时".equals(OPCValueList.get(3).get("ValueName"))){
				number= Integer.parseInt(carsMap.get("running").toString())+(int)(Double.parseDouble( OPCValueList.get(3).get("DataValue").toString()));
			}
		}else{
			number= Integer.valueOf(carsMap.get("running").toString());
		}
		List order=new ArrayList();
		order.add(number);
		List<Map<String,Object>> resultMaintenance=new ArrayList<>();
		for (Map<String,Object> map:maintenanceRecommendation){
			if(Integer.valueOf(map.get("upkeep_time").toString())>=number){
				Map<String,Object> objectMap=new HashMap<>();
				objectMap.put("upkeep_time",map.get("upkeep_time"));
				resultMaintenance.add(objectMap);
				order.add(map.get("upkeep_time"));
			}
		}
		//如果order 只有一个值，则说明没有合适保养套餐，返回所有保养套餐,如果大于1，则推荐合适保养套餐，并且返回大于该时长的所有套餐
		if(order.size()>1){
			Collections.sort(order);
			for(int i=0;i<order.size();i++){
				if(order.get(i).toString().equals(number)) {
					if (i + 1 < order.size()) {
						number = Integer.valueOf(order.get(i + 1).toString());
						break;
					} else {
						number=0;
						break;
					}
				}
			}
			result.put("upkeepTimeList",resultMaintenance);
			result.put("maintenanceRecommendation",number);
		}else{
			result.put("upkeepTimeList",maintenanceRecommendation);
			result.put("maintenanceRecommendation",number);
		}
		return result;
	}

	@Override
	public Map<String, Object> maintenanceRecommendationNew(Map<String, Object> reqMap) throws MyException {
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> carsMap = ownerDao.getCarInfoById(reqMap);
		List<Map<String, Object>> maintenanceRecommendation = upkeepDao.getUpkeep_timeByCondition(carsMap);

		String thingsId = carsMap.get("things_id").toString();
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
		// 获取车辆最新设备数据
		Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, thingsId);

		int number;
		if (null != carDataMap) {
			number = Integer.valueOf(carDataMap.get("OperatingHours").toString());
		} else {
			number = Integer.valueOf(carsMap.get("running").toString());
		}
		List order = new ArrayList();
		order.add(number);
		List<Map<String, Object>> resultMaintenance = new ArrayList<>();
		for (Map<String, Object> map : maintenanceRecommendation) {
			if (Integer.valueOf(map.get("upkeep_time").toString()) >= number) {
				Map<String, Object> objectMap = new HashMap<>();
				objectMap.put("upkeep_time", map.get("upkeep_time"));
				resultMaintenance.add(objectMap);
				order.add(map.get("upkeep_time"));
			}
		}
		//如果order 只有一个值，则说明没有合适保养套餐，返回所有保养套餐,如果大于1，则推荐合适保养套餐，并且返回大于该时长的所有套餐
		if (order.size() > 1) {
			Collections.sort(order);
			for (int i = 0; i < order.size(); i++) {
				if (order.get(i).toString().equals(number)) {
					if (i + 1 < order.size()) {
						number = Integer.valueOf(order.get(i + 1).toString());
						break;
					} else {
						number = 0;
						break;
					}
				}
			}
			result.put("upkeepTimeList", resultMaintenance);
			result.put("maintenanceRecommendation", number);
		} else {
			result.put("upkeepTimeList", maintenanceRecommendation);
			result.put("maintenanceRecommendation", number);
		}
		return result;
	}

	@Override
	public Map<String, Object> getUpkeepInfoByOrderId(Map<String, Object> reqMap) {

		List<Map<String, Object>> partsByUpkeep_id = upkeepDao.getUpkeepInfoByOrderId(reqMap);

		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("partsInfo", partsByUpkeep_id);
		return resultMap;
	}


}
